package com.campus.controller;

import com.campus.pojo.Pager;
import com.campus.pojo.SysModule;
import com.campus.pojo.SysRole;
import com.campus.pojo.SysUser;
import com.campus.service.RoleService;
import com.campus.service.UserService;
import com.campus.tools.CommonValue;
import com.campus.tools.JsonUtil;
import com.campus.tools.MD5Util;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService service;

    JsonUtil<SysUser> jsonUtil = new JsonUtil<>();
    JsonObject jsonObject = null;

    @RequestMapping("/login")
    public String login(@RequestParam("name") String name,
                        @RequestParam("psw") String password,
                        HttpServletRequest request,
                        HttpServletResponse response) throws IOException {
        SysUser user = service.login(name, MD5Util.MD5(password));
        if (user != null && user.getName() != null){
            request.getSession().setAttribute(CommonValue.USERID, user.getUserCode());
            request.getSession().setAttribute(CommonValue.USERNAME, user.getName());
            if(user.getName().equals(user.getUnitName()))
                request.getSession().setAttribute(CommonValue.UNITNAME, "欢迎您");
            else
                request.getSession().setAttribute(CommonValue.UNITNAME, user.getUnitName());
            request.getSession().setAttribute(CommonValue.USERTYPE, user.getUserType());
            request.getSession().setAttribute(CommonValue.UNITINFOID, user.getUnitId());
            request.getSession().setAttribute(CommonValue.AREANUMBER, user.getAreaId());
            request.getSession().setAttribute(CommonValue.AREATYPE, user.getAreaType());
            request.getSession().setAttribute(CommonValue.AREANAME, user.getAreaName());
            //System.out.println(user.getUnitName()+":"+user.getName());//调试
            response.sendRedirect(request.getContextPath() + "/views/index.jsp");
        }else {
            request.getSession().setAttribute(CommonValue.USERID,null);
            request.getSession().setAttribute(CommonValue.USERNAME, null);
            request.getSession().setAttribute(CommonValue.UNITNAME, null);
            request.getSession().setAttribute(CommonValue.USERTYPE, null);
            request.getSession().setAttribute(CommonValue.UNITINFOID, null);
            request.getSession().setAttribute(CommonValue.AREANUMBER, null);
            request.getSession().setAttribute(CommonValue.AREATYPE, null);
            request.getSession().setAttribute(CommonValue.AREANAME, null);
            response.sendRedirect(request.getContextPath() + "/login.jsp?rtnCode=500");
        }
        return null;
    }

    @RequestMapping(value = "/loadPermissions",method = {RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public List<SysModule> loadPermissions(String userId, HttpServletResponse response, HttpServletRequest request) throws IOException {
        List<SysModule> moduleList = service.selectModuleById(userId);
        if(moduleList == null){
            moduleList = new ArrayList<>();
        }
        //设置孩子
        for(int i=0;i<moduleList.size();i++){
            SysModule module = moduleList.get(i);
            if(module.getParentCode() == null || module.getParentCode().equals("0"))
                continue;
            for (SysModule sysModule : moduleList) {
                if (module.getParentCode().equals(sysModule.getModuleCode())) {
                    sysModule.getChildren().add(module);
                }
            }
        }
        String json = new JsonUtil<SysModule>().objectsToJSON(moduleList);//将 功能模块List 转换成Json格式
        //System.out.println(json);//调试
        response.resetBuffer();
        response.setContentType("text/html;charset=utf-8");
        response.getOutputStream().write(json.getBytes(StandardCharsets.UTF_8));
        response.getOutputStream().flush();
        return null;
    }

    @RequestMapping("/getAreaUser")
    @ResponseBody
    public Map<String,Object> getAreaUser(Integer page, Integer rows,
                                          HttpServletRequest request,
                                          HttpServletResponse response,
                                          @ModelAttribute SysUser user){  //分页获取区域管理员
        //初始化分页对象
        Pager pager = new Pager();
        pager.setCurPage(page);
        pager.setPerPageRows(rows);
        //封装查询条件
        Map<String,Object> map = new HashMap<>();
        map.put("user",user);
        //查询满足条件的所有管理员
        int count = service.count(map);
        List<SysUser> users = service.selectAreaUserByPage(user,pager);
        //封装返回结果
        Map<String,Object> result = new HashMap<>();
        result.put("total", count);
        result.put("rows", users);
        return result;
    }

    @RequestMapping("/updateAreaAdmin")
    @ResponseBody
    public void upAreaAdmin(SysUser user, HttpServletRequest request, HttpServletResponse response){
        jsonObject = new JsonObject();
        String operateId = request.getSession().getAttribute(CommonValue.USERID).toString(); // 获取登录用户的userCode
        user.setOperatorId(operateId);//设置操作人ID
        //修改时检验用户是否存在
        String exist = service.isExist(user);

        //System.out.println(exist);//调试

        if (exist.equals("exist"))
            jsonObject.addProperty("isExist", true);
        else if (exist.equals("existAdmin"))
            jsonObject.addProperty("existAdmin", true);
        else if (exist.equals("no")){
            jsonObject.addProperty("success", true);
            service.upAreaAdmin(user);
        }
        try {
            ServletOutputStream out = response.getOutputStream();
            out.write(jsonObject.toString().getBytes(StandardCharsets.UTF_8));
            out.flush();
            out.close();
        }catch (IOException ioException){
            ioException.printStackTrace();
        }
    }

    @RequestMapping("/addAreaAdmin")
    @ResponseBody
    public void addAreaAdmin(SysUser user, HttpServletRequest request, HttpServletResponse response){
        jsonObject = new JsonObject();
        String operateId = request.getSession().getAttribute(CommonValue.USERID).toString(); // 获取登录用户的userCode
        user.setOperatorId(operateId);//设置操作人ID
        user.setPsw(MD5Util.MD5(user.getPsw()));//设置加密后的密码
        user.setUserType("4");//院校管理员
        //检验用户是否存在 ， 该区是否已有管理员
        String exist = service.isExist(user);

        System.out.println(exist);//调试

        if (exist.equals("exist"))
            jsonObject.addProperty("isExist", true);
        else if (exist.equals("existAdmin"))
            jsonObject.addProperty("existAdmin", true);
        else if (exist.equals("no")){
            jsonObject.addProperty("success", true);
            service.addAreaAdmin(user);
        }
        try {
            ServletOutputStream out = response.getOutputStream();
            out.write(jsonObject.toString().getBytes(StandardCharsets.UTF_8));
            out.flush();
            out.close();
        }catch (IOException ioException){
            ioException.printStackTrace();
        }
    }

    @RequestMapping("/delUser")
    @ResponseBody
    public void delUser(String ids, HttpServletRequest request, HttpServletResponse response){
        jsonObject = new JsonObject();
        String operateId = request.getSession().getAttribute(CommonValue.USERID).toString(); // 获取登录用户的userCode
        SysUser user = new SysUser();
        //System.out.println(ids);//调试
        user.setUserCode(ids);
        user.setOperatorId(operateId);//设置操作人ID
        int count = service.deleteAreaUser(user);//删
        if (count > 0)
            jsonObject.addProperty("success", true);
        else
            jsonObject.addProperty("success", false);
        try {
            ServletOutputStream out = response.getOutputStream();
            out.write(jsonObject.toString().getBytes(StandardCharsets.UTF_8));
            out.flush();
            out.close();
        }catch (IOException ioException){
            ioException.printStackTrace();
        }
    }

    @RequestMapping("/resetPsw")
    @ResponseBody
    public void resetPsw(String userCode,HttpServletRequest request,HttpServletResponse response){
        //System.out.println(userCode);//调试
        jsonObject = new JsonObject();
        String operateId = request.getSession().getAttribute(CommonValue.USERID).toString(); // 获取登录用户的userCode
        SysUser user = new SysUser();
        user.setOperatorId(operateId);//设置操作人ID
        user.setUserCode(userCode);//设置被重置的用户
        user.setPsw(MD5Util.MD5("123456"));//重置密码为123456
        int count = service.resetPassword(user);
        if (count > 0)
            jsonObject.addProperty("success", true);
        else
            jsonObject.addProperty("success", false);
        try {
            ServletOutputStream out = response.getOutputStream();
            out.write(jsonObject.toString().getBytes(StandardCharsets.UTF_8));
            out.flush();
            out.close();
        }catch (IOException ioException){
            ioException.printStackTrace();
        }
    }

    @RequestMapping("/upPsw")
    @ResponseBody
    public void upPsw(HttpServletRequest request,HttpServletResponse response){ //修改当前登录用户的密码
        jsonObject = new JsonObject();
        String userCode = request.getParameter("userId");
        String psw_old = request.getParameter("psw_old");
        String psw_new = request.getParameter("psw_new");
        String psw_sure = request.getParameter("psw_sure");

        SysUser user = new SysUser();
        user.setOperatorId(userCode);//设置操作人ID
        user.setUserCode(userCode);//设置被重置的用户
        //检查旧密码是否正确
        SysUser u = service.selectByUserCode(userCode);
        if (u.getPsw().equals(MD5Util.MD5(psw_old))){ //正确
            //System.out.println(1);//调试
            user.setPsw(MD5Util.MD5(psw_new));
            int count = service.resetPassword(user);//修改密码
            if (count > 0)
                jsonObject.addProperty("success", true);
            else
                jsonObject.addProperty("success", false);
        }else {
            //System.out.println(2);//调试
            jsonObject.addProperty("oldPswWrong", true);
        }
        try {
            ServletOutputStream out = response.getOutputStream();
            out.write(jsonObject.toString().getBytes(StandardCharsets.UTF_8));
            out.flush();
            out.close();
        }catch (IOException ioException){
            ioException.printStackTrace();
        }
    }

    // 查询user列表
    @RequestMapping(value = "/getUser", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public Map<String, Object> getUser(Integer page, Integer rows,
                                       HttpServletRequest req,
                                       @ModelAttribute SysUser user) {
        Pager pager = new Pager();
        pager.setCurPage(page);
        pager.setPerPageRows(rows);
        String areaId = req.getSession().getAttribute("AREANUMBER").toString();
        user.setAreaId(areaId);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("user", user);
        int totalCount = service.count1(params);
        List<SysUser> users = service.selectByPage1(user, pager);
        Map<String, Object> result = new HashMap<String, Object>(2);
        result.put("total", totalCount);
        result.put("rows", users);
        return result;
    }

    // 添加用户
    @RequestMapping(value = "/addUser", method = { RequestMethod.GET, RequestMethod.POST })
    public String addUser(SysUser user, HttpServletRequest req, HttpServletResponse res) {
        // 从request中获取当前区域管理员的区域编号
        String areaId = req.getSession().getAttribute("AREANUMBER").toString();
        // 给对象user设置所属区域编号属性
        user.setAreaId(areaId);
        jsonObject = new JsonObject();
        // 从request中获取当前区域管理员用户编号
        String operateId = req.getSession().getAttribute("USERID").toString();
        // 给对象user设置操作人属性
        user.setOperatorId(operateId);
        // 给对象user设置密码属性
        user.setPsw(MD5Util.MD5(user.getPsw()));
        // 判断该用户名是否存在
        String existName = service.isExistName(user.getName(), "", areaId);
        // 判断该单位是否存在
        String existUnit = service.isExistUnit(user.getUnitId(), "", areaId);
        if (existUnit.equals("exitUnit")) {
            jsonObject.addProperty("isExistUnit", true);
        } else if (existName.equals("exit")) {
            jsonObject.addProperty("isExist", true);
        } else if (existName.equals("no")) {
            // 调用业务方法添加用户
            int result = service.addAreaAdmin(user);
            jsonObject.addProperty("success", result>0);
        }
        try {
            ServletOutputStream jos = res.getOutputStream();
            jos.write(jsonObject.toString().getBytes("utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 修改用户
    @RequestMapping(value = "/upUser", method = { RequestMethod.GET, RequestMethod.POST })
    public String upUser(SysUser user, HttpServletRequest req, HttpServletResponse res) {
        String aredId = req.getSession().getAttribute("AREANUMBER").toString();
        jsonObject = new JsonObject();
        int result = 0;
        String operateId = req.getSession().getAttribute(CommonValue.USERID).toString();
        user.setOperatorId(operateId);
        String existName = service.isExistName(user.getName(), user.getUserCode(), aredId);
        String existUnit = service.isExistUnit(user.getUnitId(), user.getUserCode(), aredId);
        if (existUnit.equals("exitUnit")) {
            jsonObject.addProperty("isExistUnit", true);
        } else if (existName.equals("exit")) {
            jsonObject.addProperty("isExist", true);
        } else if (existName.equals("no")) {
            result = service.upUser(user);
            jsonObject.addProperty("success", result);
        }
        try {
            ServletOutputStream jos = res.getOutputStream();
            jos.write(jsonObject.toString().getBytes(StandardCharsets.UTF_8));
            jos.flush();
            jos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @RequestMapping("/getCheckedRole")
    @ResponseBody
    public Map<String,Object> getCheckedRole(HttpServletRequest request,String userCode){
        String areaId = request.getSession().getAttribute("AREANUMBER").toString();
        List<String> list = service.getCheckedRole(userCode);
        Map<String ,Object> result = new HashMap<>();
        result.put("roleCodes",list);
        return result;
    }

    // 绑定新角色
    @RequestMapping(value = "/bindRole", method = { RequestMethod.GET, RequestMethod.POST })
    public String bindRole(SysUser user, HttpServletRequest req, HttpServletResponse res)
            throws UnsupportedEncodingException {
        String areaId = req.getSession().getAttribute(CommonValue.AREANUMBER).toString();
        int result = service.bindRole(user.getUserCode(), user.getRoleCodes(), areaId);
        jsonObject = new JsonObject();
        jsonObject.addProperty("success", result);
        try {
            ServletOutputStream jos = res.getOutputStream();
            jos.write(jsonObject.toString().getBytes("utf-8"));
            jos.flush();
            jos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 退出
    @RequestMapping(value = "/loginOut", method = { RequestMethod.GET, RequestMethod.POST })
    public String loginOut(HttpServletRequest req, HttpServletResponse resp) {
        req.getSession().setAttribute(CommonValue.USERID, null);
        req.getSession().setAttribute(CommonValue.UNITINFOID, null);
        req.getSession().setAttribute(CommonValue.USERNAME, null);
        req.getSession().setAttribute(CommonValue.USERTYPE, null);
        return "redirect:/views/login.jsp";
    }
}
